package com.edu.controller;

import com.edu.dao.IndexDao;
import com.edu.dao.ProductCategoryDao;
import com.edu.dao.ProductDao;
import com.edu.data.News;
import com.edu.data.Product;
import com.edu.data.ProductCategory;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/Product")
public class ProductConroller {

    //上传文件储存目录
    private static final String DESTINATION_DIR_PATH="files";
    //上传配置
    private static final int MEMORY_THRESHOLD =1024*1024; //1M
    private static final int MAX_FILE_SIZE =1024*1024*40; //40M
    private static final int MAX_REQUEST_SIZE=1024*1024*50; //50M
    private File tempDir;
    private File destinationDir;
    private String fileName;
    Map<String, String> params=new HashMap<>();

    @Autowired
    ProductDao productDao;
    @Autowired
    ProductCategoryDao productCategoryDao;

    @Autowired
    IndexDao dao;

    @RequestMapping("/selectId")
    public String indexDetail(Model model,int id) {
        Product product=productDao.getDetails(id);
        model.addAttribute("product",product);
        List<ProductCategory> productCategoryList = dao.getAllProductCategory();
        model.addAttribute("categories",productCategoryList);
        return "product-view";
    }
    @RequestMapping("/list")
    public String list(Model model) {
        List<Product> products=productDao.getAllProduct();
        List<ProductCategory> categories=productCategoryDao.getList();
        model.addAttribute("products",products);
        model.addAttribute("categories",categories);
        return "../../manage/product";
    }
    @RequestMapping("/add")
    public String add(Model model) {
        List<ProductCategory> productCategoryList = dao.getAllProductCategory();
        model.addAttribute("categories",productCategoryList);
        return "../../manage/product-modify";
    }
    @RequestMapping("/save")
    public String save(@RequestParam(value = "uploadFile", required = false) MultipartFile file,Product product) throws SQLException {
        //System.out.println("name:"+name+"desc:"+description);
        ProductCategory productCategory=productCategoryDao.findById(product.getEpcChildId());
        product.setEpcId(productCategory.getEpcParentId());
        product.setEpFileName(file.getOriginalFilename());
        productDao.add(product);
        /*//配置上传参数
        DiskFileItemFactory factory=new DiskFileItemFactory();
        //设置内存临界值-超过后将产生临时文件储存临时目录当中
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        //设置临时目录
        factory.setRepository(tempDir);

        ServletFileUpload upload=new ServletFileUpload(factory);
        //中文处理
        upload.setHeaderEncoding("UTF-8"); //设置中文编码
        //设置上传文件的最大值
        upload.setFileSizeMax(MAX_FILE_SIZE);
        //设置最大请求值
        upload.setSizeMax(MAX_REQUEST_SIZE);
        //钩爪临时路径来储存上传的文件，这个路径相对当前应用目录
        String uploadPath= req.getServletContext().getRealPath("/files")+File.separator;
        //目录不存在就创建
        File uploadDir=new File(uploadPath);
        if(!uploadDir.exists()){
            uploadDir.mkdirs();
        }
        try {
            //解析请求的内容提取文件数据
            List<FileItem> fileItems=upload.parseRequest(req);
            //迭代表单数据
            if(fileItems!=null && fileItems.size()>0){
                for (FileItem item: fileItems){
                    //获取表单需要提取的文件
                    if(!item.isFormField()){
                        fileName=new File(item.getName()).getName();
                        String filePath = uploadPath+File.separator+fileName; //获取上传的文件名字
                        File storedFile = new File(filePath);
                        item.write(storedFile);
                        req.setAttribute("message","文件提交成功");
                    }else {
                        String name1=item.getFieldName();
                        String valus=item.getString("utf-8");
                        params.put(name1,valus.trim());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

//        String name,description,photo;
//        int childId,stock,parentId;
//        Float price;
        String name=params.get("name");
        String description=params.get("description");
        String price=params.get("price");
        String stock=params.get("stock");
        String parentId=params.get("parentId");

        ProductCategory productCategory=productCategoryDao.findById(Integer.parseInt(parentId));

        Product product = new Product();
        product.setEpName(name);
        product.setEpDescription(description);
        product.setEpPrice(Double.parseDouble(price));
        product.setEpStock(Integer.parseInt(stock));
        product.setEpcId(productCategory.getEpcParentId());
        product.setEpcChildId(Integer.parseInt(parentId));
        product.setEpFileName(fileName);
        productDao.add(product);*/
        return "redirect:/Product/list";
    }
    @RequestMapping("/delete")
    public String delect(String id){
        int epid=Integer.parseInt(id);
        productDao.delect(epid);
        return "redirect:/Product/list";
    }
    @RequestMapping("/read")
    public String read(Model model,String id) throws SQLException {
        Product product= productDao.getDetails(Integer.parseInt(id));
        List<ProductCategory> productCategoryList = dao.getAllProductCategory();
        model.addAttribute("product",product);
        model.addAttribute("categories",productCategoryList);
        return "../../manage/product-update";
    }
    @RequestMapping("/update")
    public String update(Model model,Product product) throws SQLException {
        ProductCategory productCategory=productCategoryDao.findById(product.getEpcChildId());
        product.setEpcId(productCategory.getEpcParentId());
        productDao.update(product);
        return "redirect:/Product/list";
    }
    @RequestMapping("/select")
    public String select(Model model,String name,String epcid) {
        if(name!=null){
            List<Product> products=productDao.getProductLists(Integer.parseInt(epcid),name);
        }
        List<Product> products=productDao.getProductList(Integer.parseInt(epcid));
        model.addAttribute("products",products);
        System.out.println(products.size());
        List<ProductCategory> productCategoryList = dao.getAllProductCategory();
        model.addAttribute("categories",productCategoryList);
        return "../../manage/product";
    }

}
